/**
 * @desc
 *
 * @使用场景
 *
 * @author  杨晓东[of1081]
 * @company qianmi.com
 * @Date    ${DATE}
 **/
/// <reference path="./weixin-authorizer-service.d.ts" />
import * as rp from 'request-promise-native';
import CONFIG from '../config';
import SiteService from './site-service';

const HOST = 'https://api.weixin.qq.com/cgi-bin';
const appID = CONFIG.appID;

export default class WeixinService {
  /**
     * 更新AccessToken
     * @param verifyTicket
     * @returns {Promise}
     */
  static getAccessToken(verifyTicket): Promise<ComponentAccessToken> {
    return rp({
      method: 'POST',
      uri: `${HOST}/component/api_component_token`,
      body: {
        component_appid: CONFIG.appID,
        component_appsecret: CONFIG.secret,
        component_verify_ticket: verifyTicket
      },
      json: true
    }).then((data: any) => (data.errcode ? Promise.reject(data) : data));
  }

  /**
     * 获取 预授权码:
     * @param accessToken
     * @returns {Promise}
     */
  static getPreAuthCode({ accessToken }): Promise<string> {
    return rp({
      method: 'POST',
      uri: `${HOST}/component/api_create_preauthcode`,
      qs: { component_access_token: accessToken },
      body: {
        component_appid: CONFIG.appID
      },
      json: true
    }).then((data: any) => (data.errcode ? Promise.reject(data) : data.pre_auth_code));
  }

  /**
     * 生成授权的url地址
     * @param preAuthCode
     * @param redirectUri
     * @returns {string}
     */
  static getAuthUrl({ preAuthCode, redirectUri }): string {
    return `https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=${CONFIG.appID}&pre_auth_code=${preAuthCode}&redirect_uri=${redirectUri}`;
  }

  /**
     * 第三方平台对其所有API调用次数清零
     * （只与第三方平台相关，与公众号无关，接口如api_component_token）
     * @returns {Promise<any>}
     */
  static async clearQuota(): Promise<any> {
    return rp({
      method: 'POST',
      uri: `${HOST}/component/clear_quota`,
      qs: { access_token: await SiteService.getAccessToken() },
      body: {
        component_appid: CONFIG.appID
      },
      json: true
    }).then((data: any) => (data.errcode ? Promise.reject(data) : data));
  }
}
